# -*- coding: utf-8 -*-
import FPLib
from sqlalchemy import *
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base, declared_attr
from sqlalchemy.sql import text
import datetime


class TableClass(object):
    @declared_attr
    def __tablename__(cls):
        return cls.__name__.lower()
    __table_args__ = {
        'mysql_engine': 'InnoDB',
        'mysql_charset': 'utf8mb4'
    }
    __mapper_args__ = {'always_refresh': True}

    id = Column(Integer,  primary_key=True, autoincrement=True)
    # id = Column(Integer, Sequence('id_seq'), primary_key=True)

    updateAt = Column(DateTime(timezone=True), nullable=False, default=datetime.datetime.now, index=True)
    status = Column(Integer, nullable=False, default=1)

    def _load(self, data):
        # print("data::")
        # print(data)
        for (key, value) in data.items():
            if hasattr(self, key):
                setattr(self, key, value)

    def _toList(self, keys=""):
        lists = []
        res = []
        if isinstance(keys, str):
            for s in keys.split(','):
                s = s.strip()
                lists.append(s)
        if isinstance(keys, list):
            for key in keys:
                key = key.strip()
                lists.append(key)
        for key in lists:
            res.append(getattr(self, key, None))
        return res

    def _mapDict(self, dicts="", res=None):
        if not res:
            res = {}
        if isinstance(dicts, str):
            keys = dicts
            dicts = {}
            for s in keys.split(','):
                s = s.strip()
                if s:
                    dicts[s] = None

        for k in dicts.keys():
            res[k] = getattr(self, k, dicts[k])
        return res

    def _toDict(self, dicts={}):
        res = {}
        res.update(dicts)
        res.update({c.name: getattr(self, c.name, None) for c in self.__table__.columns})
        return res

Tables = declarative_base(cls=TableClass)
